﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Vita.Entities;

namespace Vita.Modules.Calendar {
  public static class CalendarExtensions {

    public static DateTime? CalculateNextProjected(this ICalendarEventSchedule schedule, DateTime? lastRunOn, DateTime? after = null) {
      var next = CalculateNextProjectedRaw(schedule, lastRunOn, after);
      if (next == null)
        return null;
      var nextValue = next.Value;
      if (nextValue > schedule.EndsOn)
        return null; 
      switch(schedule.RepeatType) {
        case RepeatType.None: case RepeatType.FixedDate: case RepeatType.Interval:
          return nextValue;  

      }
      // check for special day restrictions
      if (schedule.WeekdayMask != WeekDays.All) {

      }
      // set time of day
      if (schedule.TimeshiftMinutes != 0)
        nextValue = nextValue.Add(TimeSpan.FromMinutes(schedule.TimeshiftMinutes));
      //
      return nextValue; 
    }

    public static DateTime? CheckWeekDayMask(WeekDays mask, DateTime date) {
      return null; 
    }

    public static DateTime? CalculateNextProjectedRaw(this ICalendarEventSchedule schedule, DateTime? lastRunOn, DateTime? after = null) {
      var session = EntityHelper.GetSession(schedule);
      var lastRun = lastRunOn == null ? DateTime.MinValue : lastRunOn.Value;
      var afterDate = after == null ? session.Context.App.TimeService.Now : after.Value; 
      if (schedule.EndsOn != null && schedule.EndsOn.Value < afterDate)
        return null; 
      DateTime? result; 
      switch(schedule.RepeatType) {
        case RepeatType.None:
          return null; 
        case RepeatType.FixedDate:
          result = schedule.StartsOn < afterDate ? (DateTime?) null : schedule.StartsOn;
          return result; 
        case RepeatType.Interval:
          var sinceStart = afterDate.Subtract(schedule.StartsOn);
          var numIntervals = (int) Math.Floor(sinceStart.TotalSeconds / schedule.IntervalSeconds);
          var nextSinceStart = TimeSpan.FromSeconds((numIntervals + 1) * schedule.IntervalSeconds);
          result = schedule.StartsOn.Add(nextSinceStart);
          return result; 
        case RepeatType.Daily:
          result = afterDate.Date.AddDays(1);
          return result; 
        case RepeatType.Weekly:
          break; 

          
 
      }
      return null; 

    }//method
  }
}
